package org.linloong.core.exception;


import cn.dev33.satoken.exception.NotLoginException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.linloong.core.result.Result;
import org.linloong.core.result.ResultEnum;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Set;

/**
 * @author liuzhen
 * @date 2025/3/4
 */

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandle {

    private <T> Result<T> buildResult(Integer code, String message) {
        return Result.<T>builder()
                .code(code)
                .message(message)
                .result(false)
                .build();
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> handleValidationExceptions(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldErrors().get(0).getDefaultMessage();
        return buildResult(ResultEnum.VALID_FAIL.getCode(), message);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public Result<Void> validException(ConstraintViolationException e) {
        String message = e.getConstraintViolations().iterator().next().getMessage();
        return buildResult(ResultEnum.VALID_FAIL.getCode(), message);
    }

    @ExceptionHandler(BusinessException.class)
    public Result<Void> businessException(BusinessException e) {
        String message = e.getMessage();
        return buildResult(e.getCode(), message);
    }

    @ExceptionHandler(NotLoginException.class)
    public Result<Void> notLoginException(NotLoginException e) {
        String message = e.getMessage();
        return buildResult(ResultEnum.NOT_LOGIN.getCode(), message);
    }

    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception e) {
        log.error("系统异常", e);
        return buildResult(ResultEnum.FAIL.getCode(), "系统繁忙，请稍后重试");
    }

}
